<link rel="stylesheet" href="${base}/static/vendor/umeditor-1.2.2/themes/default/css/umeditor.css"/>
<style>
    .goods-info-panel {
        text-align: center;
        margin: 0 auto;
        padding: 10px 0 0 30%;
    }

    .goods-info-panel ul {
        list-style: none;
        text-align: center;
    }

    .goods-info-panel ul li {
        float: left;
        display: inline;
        margin: 0 30px 0 0;
        padding: 0 30px 0 0;
        font-size: 42px;
        border-right: 1px solid #e8e8e8;
    }

    .goods-info-panel ul li span {
        font-size: 12px;
        display: block;
        margin: 10px 0 5px;
        color: #8c8c8c;
    }
</style>
<div id="mainContent" class="easyui-layout" data-options="fit:true">
    <div data-options="region:'north'" style="overflow: hidden;height: 150px;">
        <table style="width: 100%;height: 100%; border: 0px;">
            <tr height="80">
                <td align="center">
                    <div class="goods-info-panel">
                        <ul>
                            <li id="total" style="color: #2b9e0a !important;"><b>${sum['total']}</b><span>商品总量</span>
                            </li>
                            <li id="a" style="color: #85c5e5 !important;"><b>${sum['a']}</b><span>现场服务</span></li>
                            <li id="b" style="color: #d07210 !important;"><b>${sum['b']}</b><span>员工福利</span></li>
                            <li id="sale" style="color: #2785d0 !important;"><b>${sum['sale']}</b><span>在售商品</span></li>
                            <li id="unSale" style="color: #8d8d8d !important;border-right: none"><b>${sum['unSale']}</b><span>下架商品</span>
                            </li>
                        </ul>
                    </div>
                </td>
            </tr>
            <tr>
                <td align="center">
                    <div style="margin: 10px auto">
                        <a id="addGoods" href="#" class="easyui-linkbutton button-orange button-xs l-btn l-btn-small">
                            <span class="l-btn-left">
                                <span class="l-btn-text" style="font-size: 16px">
                                    <i class="iconfont">&#xe6b9;</i> 新增商品
                                </span>
                            </span>
                        </a>
                    </div>
                </td>
            </tr>
        </table>
    </div>
    <div data-options="region:'center'">
        <table id="goodsDg" title="" class="easyui-datagrid"
               data-options="
                url: '${base}/admin/goods/dataList.do',
                fit:true,
                lines: true,
                rownumbers: false,
                striped: true,
                animate:true,
                singleSelect : true,
                showFooter: true,
                pagination: true,
                idField: 'goodsId',
                toolbar: '#goodsTb',
                onLoadSuccess: loadSuccess
            " border="0">
            <thead data-options="frozen:true">
            <tr>
                <th data-options="field:'imgUrl',hidden:true"></th>
                <!--<th data-options="field:'shareDes',hidden:true"></th>-->
                <th data-options="field:'companyName'" width="8%">公司</th>
                <th data-options="field:'goodsName'" width="8%">商品名称</th>
                <th data-options="field:'detailInfo',formatter:formatterGoodsInfo" width="20%">商品信息</th>
                <th data-options="field:'price',formatter:formatterPrice" width="5%">价格/元</th>
                <th data-options="field:'type',formatter:formatterType" width="5%">类别</th>
                <th data-options="field:'endTime'" width="10%">截止时间</th>
                <th data-options="field:'limitNum'" width="4%">限购人数</th>
                <th data-options="field:'sales'" width="4%">已售数量</th>
                <th data-options="field:'dataStatus',formatter:formatterStatus" width="5%">状态</th>
                <th data-options="field:'goodsId',formatter:formatterControl" width="15%">操作</th>
            </tr>
            </thead>
        </table>
    </div>
</div>


<div id="goodsTb">
    <input class="easyui-searchbox" data-options="prompt:'输入商品名称查询...',searcher:doSearch,menu:'#mm'"
           style="width:360px"/>
</div>
<div id="mm">
    <div data-options="name:'all',iconCls:'icon-refresh'">所有商品</div>
    <div data-options="name:'1',iconCls:'icon-lock'">现场服务</div>
    <div data-options="name:'2',iconCls:'icon-man'">员工福利</div>
</div>

<div id="goodsDialog" class="easyui-dialog" title="新增商品"
     data-options="
            iconCls:'icon-add',
            resizable:false,
            modal:true,
            closed: true,
            fit:true,
            onResize:function(){
                $(this).dialog('center');
            },
            queryParams: {
                goodsName: ''
            },
            buttons:[{
				text:'确定',
				iconCls: 'icon-save',
				handler:function(){
				    postGoodsFrm();
				}
			},{
				text:'取消',
				iconCls: 'icon-cancel',
				handler:function(){
				    resetForm();
				}
			}]">
    <form id="goodsFrm" action="" method="POST">
        <table class="table table-striped" border="0" cellspacing="0" cellpadding="0" style="font-size: 12px;">
            <tr>
                <td width="20%">商品名称:</td>
                <td width="80%">
                    <input name="goodsName" id="goodsName" class="easyui-textbox theme-textbox-radius"
                           data-options="required:true,prompt:'请输入100字以内的商品名称'" style="width:90%"/>
                </td>
            </tr>
            <tr>
                <td width="20%">商品分类:</td>
                <td width="80%">
                    <select id="type" name="type" class="easyui-combobox" data-options="
                    required:true,
                    editable:false" style="width:90%">
                        <option value="1" selected="selected">现场服务</option>
                        <option value="2">员工福利</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td width="20%">所属公司:</td>
                <td width="80%">
                    <input id="companyId" name="companyId" class="easyui-combobox theme-textbox-radius" data-options="
                    url:'${base}/admin/company/findCompany.do',
                    required:true,
                    editable:false,
                    valueField:'companyId',
                    textField:'companyName',
                    onLoadSuccess: function(){
                        var data = $(this).combobox('getData');
                        $(this).combobox('select', data[0].companyId);
                    }
            " style="width:90%"/>
                </td>
            </tr>
            <tr>
                <td width="20%">商品图片</td>
                <td width="80%">
                    <select id="slideImg" name="imgUrl" style="width:90%"></select>
                </td>
            </tr>
            <tr>
                <td width="20%" align="top">详情:</td>
                <td width="80%">
                    <input id="detailInfoTmp" name="detailInfo" type="hidden"/>
                    <div type="text/plain" id="detailInfo" style="width:100%;height:240px;"></div>
                </td>
            </tr>
            <tr>
                <td width="20%">价格(元）:</td>
                <td width="80%">
                    <input id="price" class="easyui-numberbox theme-textbox-radius"
                           placeholder=""
                           data-options="required:true,precision:2,prompt:'请输入商品的单个价格'" style="width:90%"/>
                    <input id="priceTmp" name="price" type="hidden"/>
                </td>
            </tr>
            <tr>
                <td width="20%">截止时间:</td>
                <td width="80%">
                    <input name="endTime" id="endTime" class="easyui-datetimebox theme-textbox-radius"
                           data-options="required:true,validType:'minDateTime'" style="width:90%"/>
                </td>
            </tr>
            <tr>
                <td width="20%">限定人数:</td>
                <td width="80%">
                    <input name="limitNum" id="limitNum" class="easyui-numberspinner theme-textbox-radius"
                           data-options="required:true,prompt:'请输入团购人数限制'" style="width:90%"/>
                </td>
            </tr>
            <tr>
                <td width="20%">上架:</td>
                <td width="80%">
                    <input id="dataStatusBtn" class="easyui-switchbutton" data-options="onText:'上架',offText:'下架'">
                    <input id="dataStatus" name="dataStatus" type="hidden">
                </td>
            </tr>
            <!--<tr>
                <td width="20%">分享抽奖描述：</td>
                <td width="80%">
                    <input type="text" name="shareDes" class="easyui-textbox theme-textbox-radius"
                           data-options="prompt: '请输入分享朋友圈的描述(100字以内)'" style="width: 90%; height:100px;"/>
                </td>
            </tr>-->
            <tr>
                <td width="20%">备注：</td>
                <td width="80%">
                    <input type="text" name="remarks" class="easyui-textbox theme-textbox-radius"
                           data-options="prompt: '请输入商品的备注信息'" style="width: 90%; height:120px;"/>
                </td>
            </tr>
        </table>
        <input id="goodsId" name="goodsId" type="hidden"/>
    </form>
</div>
<script>
    var UM_EDITOR_HOME = '${base}/static/vendor/umeditor-1.2.2/'
</script>
<script charset="utf-8" src="${base}/static/vendor/umeditor-1.2.2/third-party/template.min.js"></script>
<script charset="utf-8" src="${base}/static/vendor/umeditor-1.2.2/umeditor.config.js"></script>
<script charset="utf-8" src="${base}/static/vendor/umeditor-1.2.2/umeditor.js"></script>
<script charset="utf-8" src="${base}/static/vendor/umeditor-1.2.2/lang/zh-cn/zh-cn.js"></script>
<script>

    var editor;
    var isEdit;

    $(function () {

        editor = UM.getEditor('detailInfo');

        $('#addGoods').bind('click', function () {
            $('#goodsDialog').dialog('open');
        });

        $('#dataStatusBtn').switchbutton({
            'onChange': function (checked) {
                if (checked) {
                    $('#dataStatus').val('0');
                } else {
                    $('#dataStatus').val('2');
                }
            }
        });
        var cardview = $.extend({}, $.fn.datagrid.defaults.view, {
            renderRow: function (target, fields, frozen, rowIndex, rowData) {

                if (rowData.imgUrl != undefined) {
                    var cc = [];
                    cc.push('<td colspan=' + fields.length + ' style="padding:5px;border:0;">');
                    var img = rowData.imgUrl;
                    cc.push('<img src="' + img + '" style="width:150px;float:left">');
                    cc.push('<div style="float:left;margin-left:10px;width:200px;">');
                    for (var i = 0; i < fields.length; i++) {
                        if (fields[i] != 'imgId') {
                            var copts = $(target).datagrid('getColumnOption', fields[i]);
                            if (fields[i] == 'imgSize') {
                                var size = parseInt(rowData[fields[i]]);
                                var sizeTxt = size + ' B';
                                if (size > 1024 && size < 1024 * 1024) {
                                    sizeTxt = (size / 1024).toFixed(2) + ' KB';
                                } else if (size > 1024 * 1024) {
                                    sizeTxt = (size / (1024 * 1024)).toFixed(2) + ' MB';
                                }
                                cc.push('<p><span class="c-label">' + copts.title +
                                    ':</span> ' + sizeTxt + '</p>');
                            } else {
                                cc.push('<p><span class="c-label">' + copts.title + ':</span> ' + rowData[fields[i]] + '</p>');
                            }
                        }
                    }
                    cc.push('</div>');
                    cc.push('</td>');
                    return cc.join('');
                }

                return '<td colspan=' + fields.length + ' style="padding:5px;border:0;"><font color="#ff0000">请先添加商品展示图片!!!</font></td>'

            }
        });
        $('#slideImg').combogrid({
            mode: 'remote',
            url: '${base}/admin/imglib/getUnUsedImgs.do',
            required: true,
            multiple: true,
            width: '80%',
            panelWidth: 650,
            panelHeight: 400,
            idField: 'imgId',
            textField: 'imgName',
            view: cardview,
            columns: [[
                {field: 'imgId', hidden: true},
                {field: 'goodsId', hidden: true},
                {field: 'imgName', title: '名称', width: 180, sortable: true},
                {field: 'imgUrl', title: '地址', width: 200, sortable: true},
                {field: 'imgType', title: '类型', width: 100, sortable: true},
                {field: 'imgSize', title: '大小', width: 100, sortable: true}
            ]]
        });

        $('#goodsFrm').form({
            'onLoadSuccess': function (data) {
                if (isEdit) {
                    $('#slideImg').combogrid({url: '/admin/imglib/getUnUsedImgs.do?cId=' + data.goodsId})
                }
                if (data.dataStatus == '0') {
                    $('#dataStatusBtn').switchbutton('check');
                } else {
                    $('#dataStatusBtn').switchbutton('uncheck');
                }
                $('#price').numberbox('setValue', data.price / 100);

                editor.execCommand('cleardoc');

                editor.execCommand('insertHtml', data.detailInfo);

                if (data.imgUrl && typeof(data.imgUrl) != "undefined") {
                    var imgIds = data.imgUrl.split(',');
                    var imgIdArr = new Array();
                    for (var imgId in imgIds) {
                        imgIdArr.push(imgIds[imgId]);
                    }
                    $('#slideImg').combogrid('setValues', imgIdArr);
                }
            }
        });
    });

    function formatterGoodsInfo(val, row) {
        return val.replace(/<[^>]+>/g, "");
    }

    function formatterPrice(val, row) {
        return val / 100;
    }

    function formatterType(val, row) {
        if (val == '1') {
            return '现场服务';
        }

        return '员工福利';
    }

    function formatterStatus(val, row) {
        if (val == '0') {
            return '<span style="color:#008000">出售中</span>';
        }

        return '<span style="color:#ff0000">已结束</span>';
    }

    function formatterControl(val, row) {
        var edit = '<a class="editBtn" href="#">修改</a>';
        var sale = '<a class="saleBtn" href="#">上架</a>';
        var down = '<a class="downBtn" href="#">下架</a>';

        return edit + '&nbsp;&nbsp;' + sale + '&nbsp;&nbsp;' + down;
    }

    function loadSuccess(data) {

        var dc = $('#mainContent').find('.editBtn, .saleBtn, .downBtn');
        if (dc.length < 1) {
            return;
        }

        $(dc).each(function (r, d) {
            var index = Math.floor(r / 3);
            var cls = $(this).attr('class');
            var goods = data.rows[index];

            if (cls == 'editBtn') {
                $(this).linkbutton({
                    plain: true,
                    iconCls: 'icon-edit',
                    onClick: function () {
                        editGoods(goods);
                    }
                });
                if (goods.dataStatus == '2') {
                    $(this).linkbutton({disabled: true});
                }
            } else if (cls == 'saleBtn') {
                $(this).linkbutton({
                    plain: true,
                    iconCls: 'icon-refresh',
                    onClick: function () {
                        sale(goods);
                    }
                });
                if (goods.dataStatus == '0') {
                    $(this).linkbutton({disabled: true});
                }
            } else if (cls == 'downBtn') {
                $(this).linkbutton({
                    plain: true,
                    iconCls: 'icon-remove',
                    onClick: function () {
                        down(goods);
                    }
                });
                if (goods.dataStatus == '2') {
                    $(this).linkbutton({disabled: true});
                }
            }
        });
    }

    function editGoods(goods) {
        isEdit = true;
        $('#goodsFrm').form('clear').form('load', goods);
        $('#goodsDialog').dialog({title: '修改商品', iconCls: 'icon-edit', closed: false});
    }

    function postGoodsFrm() {
        $.messager.progress();
        var url = "${base}/admin/goods/add.do";
        if (isEdit) {
            url = "${base}/admin/goods/update.do";
        }
        $('#goodsFrm').form('submit', {
            url: url,
            onSubmit: function () {
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');
                } else {
                    $('#detailInfoTmp').val(editor.getContent());
                    $('#priceTmp').val(Math.round($('#price').numberbox('getValue') * 100));
                }

                return isValid;
            },
            success: function (data) {
                $.messager.progress('close');
                var r = JSON.parse(data);
                if (r.ok) {
                    $('#goodsDialog').dialog('close');
                    $('#goodsDg').datagrid('reload');
                    if (!isEdit) {
                        showMsg('操作成功', '新增商品成功!');
                    } else {
                        showMsg('操作成功', '修改商品成功!')
                    }
                    refreshSumInfo();
                    resetForm();
                } else {
                    showMsg('操作失败', r.msg);
                }
            }
        });
    }

    function sale(goods) {
        $.post('${base}/admin/goods/update.do',
            {
                goodsId: goods.goodsId,
                goodsName:goods.goodsName,
                dataStatus: 0
            },
            function (resp) {
                if (resp.ok) {
                    showMsg('操作成功', '商品上架成功!');
                    refreshSumInfo();
                    $('#goodsDg').datagrid('reload');
                } else {
                    showMsg('操作失败', '商品上架失败!');
                }
        }, 'json');
    }

    function down(goods) {
        $.post('${base}/admin/goods/update.do',
            {
                goodsId: goods.goodsId,
                goodsName:goods.goodsName,
                dataStatus: 2
            },
            function (resp) {
                if (resp.ok) {
                    showMsg('操作成功', '商品下架成功!');
                    $('#goodsDg').datagrid('reload');
                    refreshSumInfo();
                } else {
                    showMsg('操作失败', '商品下架失败!');
                }
        }, 'json');
    }

    function refreshSumInfo() {
        $.post('${base}/admin/goods/getGoodsSum.do', {}, function (data) {
            $('#total').children('b').text(data.total);
            $('#a').children('b').text(data.a);
            $('#b').children('b').text(data.b);
            $('#sale').children('b').text(data.sale);
            $('#unSale').children('b').text(data.unSale);
        }, 'json');
    }

    function doSearch(value, name) {
        var goods = $('#goodsDg').datagrid('options').queryParams;
        goods.goodsName = name + ',' + value;

        $('#goodsDg').datagrid({'pageNumber': 1});
        $('#goodsDg').datagrid('reload');
    }

    function resetForm() {
        isEdit = false;
        $('#goodsFrm').form('clear');
        $('#slideImg').combogrid({url: '${base}/admin/imglib/getUnUsedImgs.do'});
        isEdit = false;
        $('#goodsDialog').dialog({
            title: '新增商品',
            iconCls: 'icon-add',
            closed: true
        });
    }

    $.extend($.fn.validatebox.defaults.rules, {
        minDateTime: {
            validator: function (value, param) {
                return value > new Date().format('yyyy-MM-dd hh:mm:ss');
            },
            message: '请输入大于当前时间的结束日期.'
        }
    });
</script>